package com.zhkj.txg.module.order.ui.group

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.google.gson.Gson
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.ShopActivity
import com.zhkj.txg.module.order.adapter.OrderListAdapter
import com.zhkj.txg.module.order.entity.OrderListEntity
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.entity.OrderSubmitEntity
import com.zhkj.txg.module.order.popup.OrderReceivePopupWindow
import com.zhkj.txg.module.order.popup.PayTypePopupWindow
import com.zhkj.txg.module.order.ui.OrderDetailActivity
import com.zhkj.txg.module.order.ui.OrderEvaluatePublishActivity
import com.zhkj.txg.module.order.ui.OrderShippingActivity
import com.zhkj.txg.module.order.vm.OrderViewModel
import com.zhkj.txg.module.product.popup.ProductSharePopupWindow
import com.zhkj.txg.module.product.ui.ProductShareActivity
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.PayUtils
import com.zhkj.txg.utils.ShareUtils
import com.zhkj.txg.utils.WXPayEntity
import kotlinx.android.synthetic.main.fragment_order_list.*

class GroupOrderListFragment : ViewModelFragment<OrderViewModel>() {

    companion object {
        private val TYPE = "type"
        fun newInstance(type: String): GroupOrderListFragment {
            val fragment = GroupOrderListFragment()
            fragment.arguments = Bundle().apply {
                putString(TYPE, type)
            }
            return fragment
        }
    }

    override fun setViewModel(): OrderViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_order_list

    // 订单列表点击事件
    private val listener = OnItemChildClickListener { adapter, view, position ->
        (adapter.data[position] as? OrderListEntity)?.let { order ->
            when (view.id) {
                // 打开店铺
                R.id.tvOrderListShopName -> order.shops?.let {
                    if (it.id > 0) ShopActivity.open(requireContext(), it.shopName, it.id)
                }
                R.id.ivOrderListShop -> order.shops?.let {
                    if (it.id > 0) ShopActivity.open(requireContext(), it.shopName, it.id)
                }
                //取消订单
                R.id.tvOrderListCancel -> viewModel.cancelOrder(AccountManager.getToken(), order.id, position, true)
                // 立即支付
                R.id.tvOrderListPay -> showPayPopup(
                    OrderSubmitEntity(
                        order.totalAmount?.toDouble() ?: 0.0,
                        order.orderSignNumber
                    ).apply {
                        orderId = order.id
                        uiPosition = position
                    })
                //查看物流
                R.id.tvOrderListShipping -> OrderShippingActivity.start(
                    requireActivity(), order.id, true
                )
                // 确认收货
                R.id.tvOrderListConfirm -> {
                    receivePopupWindow.setData(position, order.id)
                    receivePopupWindow.showPopupWindow()
                }
                // 申请退款
                R.id.tvOrderListRefund -> OrderDetailActivity.open(requireContext(), order.id, true)
                // 评价
                R.id.tvOrderListEvaluate -> OrderEvaluatePublishActivity.open(
                    requireActivity(),
                    order.id,
                    order.goods,
                    true
                )
                // 删除订单
                R.id.tvOrderListDelete -> viewModel.deleteOrder(order.id, position, true)
                R.id.rvOrderListGoods -> OrderDetailActivity.open(requireActivity(), order.id, true)
                R.id.text_share -> {
                    with(sharePopupWindow) {
                        order.goods[0].let {
                            setQRcode(View.GONE)
                            productName = it.goodsName
                            productPrice = it.goodsPrice
                            productImage = mutableListOf(it.image)
                            goodsId = it.goodsId
                            shareUrl = order.share_url
                            showPopupWindow()
                        }
                    }
                }
                else -> Unit
            }
        }
    }

    private val sharePopupWindow: ProductSharePopupWindow by lazy {
        ProductSharePopupWindow(requireContext()) { type ->
            when (type) {
                2 -> {
                    if (sharePopupWindow.productImage.isNotEmpty()) ProductShareActivity.open(
                        requireActivity(), sharePopupWindow.goodsId,
                        sharePopupWindow.productImage.toTypedArray(),
                        sharePopupWindow.productName,
                        sharePopupWindow.productPrice
                    ) else toast(getString(R.string.empty_gallery))
                }
                1 -> ShareUtils.shareUrl2Friends(
                    requireContext(),
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl
                )
                else -> ShareUtils.shareUrl2Friends(
                    requireContext(),
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl,
                    true
                )
            }
        }
    }

    // 订单列表Adapter
    private val orderListAdapter = OrderListAdapter(1).apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.groupOrderList(AccountManager.getToken())
        }
        setOnItemClickListener { _, _, position ->
            OrderDetailActivity.open(requireActivity(), data[position].id, true)
        }
        setOnItemChildClickListener(listener)
    }

    // 选择支付方式的popup
    private val payTypePopupWindow: PayTypePopupWindow by lazy {
        PayTypePopupWindow(requireContext(), { type, orderInfo ->
            viewModel.groupPayOrder(
                AccountManager.getToken(), orderInfo.orderId,
                orderInfo.orderSignNumber, type, orderInfo.uiPosition
            )
        }, { false })
    }

    // 确认收货的popup
    private val receivePopupWindow: OrderReceivePopupWindow by lazy {
        OrderReceivePopupWindow(requireContext()) { uiPosition, orderId ->
            viewModel.receiveOrder(AccountManager.getToken(), uiPosition, orderId, true)
        }
    }

    private var refresh: Boolean = false

    override fun initViewModel() {
        // 订单列表数据观察者
        viewModel.orderType = arguments?.getString(TYPE) ?: Type.ALL.type
        viewModel.orderListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshOrder.finishRefresh()
                    else if (it.hasMore) orderListAdapter.loadMoreModule?.loadMoreComplete()
                    else orderListAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) orderListAdapter.addData(it.data)
                    else orderListAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) orderListAdapter.loadMoreModule?.loadMoreFail()
                    else refreshOrder.finishRefresh(false)
                }
            }
        })
        // 订单取消观察者
        viewModel.orderCancelLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.order_cancel_success))
                refreshItem(it.uiPosition, cancel = true)
            }
        })
        // 订单支付观察者
        viewModel.payOrderLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                if (!order.isNeedPay) {
                    toast(getString(R.string.pay_success))
                    payTypePopupWindow.dismiss()
                    refreshItem(order.uiPosition, pay = true)
                    // 刷新余额
                    RxBus.post(BalanceChangeEvent())
                } else when (order.payType) {
                    // 微信支付
                    OrderPayEntity.TYPE_WECHAT -> {
                        order.payInfo.let {
                            val entity = Gson().fromJson(it, WXPayEntity::class.java)
                            PayUtils.wxPay(requireContext(), entity, order.uiPosition)
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(requireActivity(), order.payInfo, {
                        toast(getString(R.string.pay_success))
                        refreshItem(order.uiPosition, pay = true)
                        payTypePopupWindow.dismiss()
                    }, { toast(it) })
                    else -> Unit
                }
            }
        })
        // 订单列表刷新观察者
        viewModel.orderListStatusSubscribe().observe(this, Observer { typeList ->
            // 当前列表页的状态
            val type = arguments?.getString(TYPE)
            // 当前页面是全部列表页，并且没有显示
            val isAllAndNeedRefresh = type == Type.ALL.type && (isHidden || !isResumed)
            // 当前列表在需要刷新的类型中,并且没有显示
            val needRefresh = typeList.refreshType.any { it.type == type } && ((isHidden || !isResumed))
            if (isAllAndNeedRefresh || needRefresh) refresh = true
        })
        // 订单支付成功观察者
        viewModel.payResult().observe(viewLifecycleOwner, Observer {
            if (it.paySuccess) {
                toast(getString(R.string.pay_success))
                refreshItem(it.uiPosition, pay = true)
                payTypePopupWindow.dismiss()
            }
        })
        // 订单确认收货观察者
        viewModel.receiveOrderLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.order_receive_success))
                refreshItem(it.uiPosition, receive = true)
            }
        })
        // 删除订单观察者
        viewModel.deleteOrderLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.delete_success))
                refreshItem(it.uiPosition, delete = true)
            }
        })
    }

    override fun initUI() {
        with(rvOrderList) {
            layoutManager = LinearLayoutManager(context)
            adapter = orderListAdapter
        }
        orderListAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshOrder.setOnRefreshListener { initData() }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden && refresh) {
            initData()
            refresh = false
        }
    }

    override fun onResume() {
        super.onResume()
        if (refresh) {
            initData()
            refresh = false
        }
    }

    override fun initData() {
        viewModel.groupOrderList(AccountManager.getToken(), true)
    }

    /**
     * 显示支付按钮
     * @param it 数据对象，包含金额、订单号、订单ID、订单对应的列表位置
     */
    private fun showPayPopup(it: OrderSubmitEntity) {
        payTypePopupWindow.run {
            setData(it)
            showPopupWindow()
        }
    }

    /**
     * 刷新当前列表页的item，并通知相应状态列表页刷新
     * @param position 列表中的位置
     * @param pay 状态变成已支付
     * @param receive 状态变成已收货
     * @param cancel 状态变成以已取消
     */
    private fun refreshItem(
        position: Int,
        pay: Boolean = false,
        receive: Boolean = false,
        cancel: Boolean = false,
        delete: Boolean = false
    ) {
        // 刷新当前页面
        if (viewModel.orderType == Type.ALL.type && !delete) {// 全部列表只需要修改数据，不需要重新请求数据
            orderListAdapter.data[position].orderStatus = when {
                pay -> "1"
                cancel -> "3"
                receive -> "2"
                else -> orderListAdapter.data[position].orderStatus
            }
            if (pay) orderListAdapter.data[position].payStatus = "1"
            if (receive) orderListAdapter.data[position].shippingStatus = "1"
            orderListAdapter.notifyItemChanged(position)
        } else orderListAdapter.remove(position)// 其他列表页状态改变，直接删掉item
        // 发送刷新其他页面的通知
        RxBus.post(
            OrderListRefreshEvent(
                when {
//                    pay -> listOf(Type.PAY, Type.SEND)
//                    receive -> listOf(Type.SEND, Type.RECEIVE, Type.COMPLETE)
//                    pay -> listOf(Type.ING)
//                    receive -> listOf(Type.SUCCESS, Type.FAIL)
                    else -> listOf(Type.ALL)
                }
            )
        )
    }
}

class OrderListRefreshEvent(
    /**
     * 需要刷新的列表类型数组
     */
    val refreshType: List<Type>
)